﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;
using DuJianliang.ApplicationPlatform.Common;

namespace DuJianliang.ApplicationPlatform.UserPermission
{
    public partial class SetUserPermission : System.Web.UI.Page
    {
        UserPermissionBll userPermissionBll = new UserPermissionBll();

        public string UserID
        {
            set
            {
                ViewState["UserID"] = value;
            }
            get
            {
                return ViewState["UserID"] != null ? ViewState["UserID"].ToString() : string.Empty;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                UserPermissionBll userPermissionBll = new UserPermissionBll();
                if (!userPermissionBll.HasPermission(CurrentInfo.Instance.CurrentUser.ID, (int)Permission.UserPermission))
                {
                    Response.Write("您没有权限使用该功能");
                    Response.End();
                    return;
                }

                this.UserID = Request.QueryString["userid"];

                InitCheckBoxList();
                InitTreeView();
            }
        }

        private void InitCheckBoxList()
        {
            if (string.IsNullOrWhiteSpace(this.UserID))
            {
                return;
            }

            ckList.Items.Clear();

            DataTable dataTable1 = userPermissionBll.GetPermissionDataTable();
            ckList.DataSource = dataTable1;
            ckList.DataTextField = "PermissionName";
            ckList.DataValueField = "PermissionID";
            ckList.DataBind();
            

            DataTable dataTable2 = userPermissionBll.GetUserPermissionDataTable(this.UserID);
            foreach (DataRow dataRow in dataTable2.Rows)
            {
                ListItem listItem = ckList.Items.FindByValue(dataRow["PermissionID"].ToString());
                listItem.Selected = true;
            }
        }

        protected void btnOK_Click(object sender, EventArgs e)
        {
            try
            {
                UpdateData();
                InitCheckBoxList();

                UpdateTreeViewData();

                Response.Redirect("UserList.aspx"); 
            }
            catch
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('保存失败');</script>"); 
            }            
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("UserList.aspx");
        }

        private void UpdateData()
        {
            if (string.IsNullOrWhiteSpace(this.UserID))
            {
                return;
            }

            string sql_delete = @"DELETE FROM dbo.t5715_UserPermission WHERE UserID  = @UserID";

            string sql_insert = @"INSERT INTO dbo.t5715_UserPermission
                                               ([UserID]
                                               ,[PermissionID])
                                         VALUES
                                               (@UserID
                                               ,@PermissionID)";

            Database database = DatabaseFactory.CreateDatabase();
            DbConnection dbConnection = null;
            DbTransaction dbTransaction = null;
            DbCommand dbCommand = null;
            List<DbCommand> dbCommandList = new List<DbCommand>();

            try
            {
                dbCommand = database.GetSqlStringCommand(sql_delete);
                database.AddInParameter(dbCommand, "@UserID", DbType.String, this.UserID);
                dbCommandList.Add(dbCommand);

                foreach (ListItem listItem in ckList.Items)
                {
                    if (listItem.Selected)
                    {
                        dbCommand = database.GetSqlStringCommand(sql_insert);
                        database.AddInParameter(dbCommand, "@UserID", DbType.String, this.UserID);
                        database.AddInParameter(dbCommand, "@PermissionID", DbType.String, listItem.Value);
                        dbCommandList.Add(dbCommand);
                    }
                }

                dbConnection = database.CreateConnection();
                dbConnection.Open();
                dbTransaction = dbConnection.BeginTransaction();

                foreach (DbCommand dbCmd in dbCommandList)
                {
                    database.ExecuteNonQuery(dbCmd, dbTransaction);
                }

                dbTransaction.Commit();                
            }
            catch (Exception ex)
            {
                if (dbTransaction != null)
                {
                    dbTransaction.Rollback();
                }                
                throw ex;
            }
            finally
            {
                if (dbConnection != null && dbConnection.State != ConnectionState.Closed)
                {
                    dbConnection.Close();
                }
            }
        }


        #region 选择检验员在工序中可检验的部门

        private void InitTreeView()
        {
            tvDept.Nodes.Clear();
            TreeNode node = new TreeNode();
            node.Value = "0";
            node.Text = "选择检验员在工序中可检验的部门";
            node.Target = "0";
            node.SelectAction = TreeNodeSelectAction.None;
            tvDept.Nodes.Add(node);

            DataTable dataTable = userPermissionBll.GetDeptDataTable();
            DataTable selectedDetp = this.GetSelectedDept();

            InitTreeNode(dataTable, "0", node, selectedDetp);

            tvDept.ExpandAll();
        }

        private void InitTreeNode(DataTable dataTable, string deptID, TreeNode treeNode, DataTable selectedDept)
        {
            DataRow[] dataRows = dataTable.Select(string.Format("ParentDeptID={0}", deptID));
            foreach (DataRow dataRow in dataRows)
            {
                TreeNode node = new TreeNode();
                node.Text = dataRow["DeptName"].ToString();
                node.Value = dataRow["DeptID"].ToString();
                node.Target = dataRow["DeptLevel"].ToString();
                node.SelectAction = TreeNodeSelectAction.None;

                if (selectedDept.Select(string.Format("DeptID={0}", node.Value)).Length > 0)
                {
                    node.Checked = true;
                }

                treeNode.ChildNodes.Add(node);
                InitTreeNode(dataTable, node.Value, node, selectedDept);
            }
        }

        private void GetSelectedDeptID(TreeNode treeNode, List<string> deptList)
        {
            foreach (TreeNode node in treeNode.ChildNodes)
            {
                if (node.Checked)
                {
                    deptList.Add(node.Value);
                }
                GetSelectedDeptID(node, deptList);
            }
        }

        public DataTable GetSelectedDept()
        {
            string sql = @"SELECT * FROM [dbo].[t5715_UserProcessCheckSettings] WHERE UserID = @UserID";

            try
            {
                Database database = DatabaseFactory.CreateDatabase();
                DbCommand dbCommand = database.GetSqlStringCommand(sql);
                database.AddInParameter(dbCommand, "@UserID", DbType.String, this.UserID);
                return database.ExecuteDataSet(dbCommand).Tables[0];
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public void UpdateTreeViewData()
        {
            if (string.IsNullOrWhiteSpace(CurrentInfo.Instance.CurrentUser.ID))
            {
                return;
            }

            string sql_delete = @"DELETE FROM [dbo].[t5715_UserProcessCheckSettings] WHERE UserID = @UserID";
            string sql_insert = @"INSERT INTO [dbo].[t5715_UserProcessCheckSettings]
                                           ([UserID]
                                           ,[DeptID])
                                     VALUES
                                           (@UserID
                                           ,@DeptID)";

            List<string> deptList = new List<string>();
            GetSelectedDeptID(tvDept.Nodes[0], deptList);

            try
            {
                Database database = DatabaseFactory.CreateDatabase();
                DbCommand dbCommand = database.GetSqlStringCommand(sql_delete);
                database.AddInParameter(dbCommand, "@UserID", DbType.String, this.UserID);
                database.ExecuteNonQuery(dbCommand);

                foreach (string deptID in deptList)
                {
                    dbCommand = database.GetSqlStringCommand(sql_insert);
                    database.AddInParameter(dbCommand, "@UserID", DbType.String, this.UserID);
                    database.AddInParameter(dbCommand, "@DeptID", DbType.String, deptID);
                    database.ExecuteNonQuery(dbCommand);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #endregion
    }
}